//
//  XMPPManager.m
//  XMPPManager
//
//  Created by cocoajin on 14-4-17.
//  Copyright (c) 2014年 com.9ask. All rights reserved.
//

#import "XMPPManager.h"
//#import <RobotSDK/RobotSDK.h>
static XMPPManager *manager = nil;

@interface XMPPManager ()
{
//    NSString *theHostIP;
    NSString *theUserName;
    NSString *thePasswrod;
}

@end

@implementation XMPPManager

#pragma mark public method
+ (XMPPManager*)manager
{
    if (manager == nil)
    {
        @synchronized(self)
        {
            if (manager == nil)
            {
                manager = [[super alloc] init];
            }
        }
    }
    return manager;
}
- (id)init
{
    if (self = [super init])
    {
        self.messageType_str=@"user-say";
        self.content_str=@"办理财";
        self.corpId_str=@"1";
        self.bizId_str=@"702282302503391232";
        self.type_str=@"endpoint-ios-event";
    

        //
        
    }
    return self;
}
-(void)setXMPPConfig
{

}


- (void)setUserName:(NSString *)userName password:(NSString *)pwd
{
    theUserName = userName;
    thePasswrod = pwd;
}

- (void)setUpStream
{
    self.xmppStream = [[XMPPStream alloc]init];
    if (self.theHostIP==nil || thePasswrod==nil || theUserName==nil)
    {
        //        NSLog(@" -- 服务器连接错误111111：ip、用户名、密码 不能为空。");
    }
    XMPPJID *jid = [XMPPJID jidWithUser:theUserName domain:@"guiji.ai" resource:@"dhrtc"];
    [_xmppStream setMyJID:jid];
    [_xmppStream setHostName:self.theHostIP];
    [self.xmppStream setHostPort:5222]; //设置xmpp端口，默认5222
    
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.xmppStream setKeepAliveInterval:30]; //心跳包时间
    
}

- (BOOL)connectServer
{
    [self setUpStream];
    
    if (![_xmppStream isDisconnected]) {
        return YES;
    }
    

    NSError *connectError = nil;
    if (![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&connectError]) {
//        NSLog(@" -- 服务器连接错误：%@",connectError);
        
        return NO;
    }
    return YES;
}

- (void)disConnect
{
    [self goOffLine];
    [_xmppStream disconnect];
}

- (void)goOnLine
{
    XMPPPresence *presence = [XMPPPresence presence];
    NSString *domain =[_xmppStream.myJID domain];
//    NSLog(@"domain:%@",domain);
    //Google set their presence priority to 24, so we do the same to be compatible.
    
    if([domain isEqualToString:@"gmail.com"]
       || [domain isEqualToString:@"gtalk.com"]
       || [domain isEqualToString:@"talk.google.com"])
    {
        NSXMLElement *priority = [NSXMLElement elementWithName:@"priority" stringValue:@"24"];
        [presence addChild:priority];
    }
    [_xmppStream sendElement:presence];
    
    if ([self.delegate respondsToSelector:@selector(userLoginSuccess:)]) {
        [self.delegate userLoginSuccess:_xmppStream.myJID];
    }
}

- (void)goOffLine
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    
    [_xmppStream sendElement:presence];
}
- (void)toUserSayMessage
{
    NSString * messageType=@"user-say";//@"user-say";
    NSString * content=self.content_str;//@"办理财";
    NSString * corpId=self.corpId_str;//@"1";
    NSString * bizId=self.bizId_str;//@"702256877429460992";
    NSString * type=self.type_str;//@"endpoint-ios-event";
    NSDictionary* messageDic = @{@"messageType":messageType,@"content":content,@"corpId":corpId,@"bizId":bizId};
    NSDictionary* bodydic = @{@"type":type,@"message":messageDic};
    
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodydic options:NSJSONWritingPrettyPrinted error:nil];
    if (bodyData!=nil)
    {
            NSString *body_str = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
         NSString *toStr = @"im-control-server@guiji.ai";
         
         NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
         [body setStringValue:body_str];
         NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
         [message addAttributeWithName:@"type" stringValue:@"chat"];
         [message addAttributeWithName:@"to" stringValue:toStr];
         [message addChild:body];

        
         
//         NSLog(@"发送消息给XMPP:%@",message);
         
         [_xmppStream sendElement:message];
    }

        
}
- (void)toSendReplaceVariable:(NSString*)variableMap
{
    NSString * messageType=@"replaceVariable";//@"user-say";
//    NSString * content=self.content_str;//@"办理财";
 //   NSString * corpId=self.corpId_str;//@"1";
  //  NSString * bizId=self.bizId_str;//@"702256877429460992";
    NSString * type=self.type_str;//@"endpoint-ios-event";
    NSData *mydata = [variableMap dataUsingEncoding:NSUTF8StringEncoding];
    if (mydata==nil) {
        return;
    }
    NSDictionary *variableMap_dic = [NSJSONSerialization JSONObjectWithData:mydata options:0 error:nil];

    NSDictionary* messageDic = @{@"messageType":messageType,@"variableMap":variableMap_dic};
    NSDictionary* bodydic = @{@"type":type,@"message":messageDic};
    
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodydic options:NSJSONWritingPrettyPrinted error:nil];
    if (bodyData!=nil)
    {
        NSString *body_str = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
         NSString *toStr = @"im-control-server@guiji.ai";
         
         NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
         [body setStringValue:body_str];
         NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
         [message addAttributeWithName:@"type" stringValue:@"chat"];
         [message addAttributeWithName:@"to" stringValue:toStr];
         [message addChild:body];

        
         
         NSLog(@"发送消息给XMPP:%@",message);
         
         [_xmppStream sendElement:message];
    }

        
}
- (void)toStartMessage
{
    NSString * messageType=@"start";//@"user-say";
    NSString * content=self.content_str;//@"办理财";
    NSString * corpId=self.corpId_str;//@"1";
    NSString * bizId=self.bizId_str;//@"702256877429460992";
    NSString * type=self.type_str;//@"endpoint-ios-event";
    NSDictionary *  variabledic=self.variable_dic;
    NSDictionary * callinfodic=self.callInfo_dic;
    NSDictionary* messageDic = @{@"messageType":messageType,@"content":content,@"corpId":corpId,@"bizId":bizId,@"variable":variabledic,@"callInfo":callinfodic};
    NSDictionary* bodydic = @{@"type":type,@"message":messageDic};
    NSLog(@"bodydic:%@,content:%@",bodydic,content);
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodydic options:NSJSONWritingPrettyPrinted error:nil];
    if (bodyData!=nil)
    {
            NSString *body_str = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
         NSString *toStr = @"im-control-server@guiji.ai";
         
         NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
         [body setStringValue:body_str];
         NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
         [message addAttributeWithName:@"type" stringValue:@"chat"];
         [message addAttributeWithName:@"to" stringValue:toStr];
         [message addChild:body];

        
         
         NSLog(@"发送消息给XMPP:%@",message);
         
         [_xmppStream sendElement:message];
    }

        
}
- (void)sendPersonMessage
{
    NSString * messageType=self.messageType_str;//@"user-say";
    NSString * content=self.content_str;//@"办理财";
    NSString * corpId=self.corpId_str;//@"1";
    NSString * bizId=self.bizId_str;//@"702256877429460992";
    NSString * type=self.type_str;//@"endpoint-ios-event";
    NSDictionary* messageDic = @{@"messageType":messageType,@"content":content,@"corpId":corpId,@"bizId":bizId};
    NSDictionary* bodydic = @{@"type":type,@"message":messageDic};
    
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodydic options:NSJSONWritingPrettyPrinted error:nil];
    if (bodyData!=nil)
    {
            NSString *body_str = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
         NSString *toStr = @"im-control-server@guiji.ai";
         
         NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
         [body setStringValue:body_str];
         NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
         [message addAttributeWithName:@"type" stringValue:@"chat"];
         [message addAttributeWithName:@"to" stringValue:toStr];
         [message addChild:body];

        
         
         NSLog(@"发送消息给XMPP:%@",message);
         
         [_xmppStream sendElement:message];
    }

        
}
- (void)sendMessage
{
    NSDictionary* bodydic = @{
        
        @"method":@"MakeNewSession",
        
        @"params":@{
            
            @"sessionId":@"2bd3fa34-21da-4762-8fdc-7e92e4cec8b4",
            
            @"dumpSession":@1,
            
            @"data":@{
                
                @"bg_img":@"https://robot.guiji.ai/nfs/duix-cc/background/MetaHumanSample.png",
                
                @"sequence":@[
                    
                    @"https://kun.guiji.ai/model/2021/10/14/25dea00922e94b7b83996447abb6fb86.mp4"
                    
                ],
                
                @"udCode":@"213354538352709"
                
            }
            
        },
        
        @"id":@0
        
    };
    
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodydic options:NSJSONWritingPrettyPrinted error:nil];
    if (bodyData!=nil)
    {
            NSString *body_str = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
         NSString *toStr = @"dev_6_18@guiji.ai";
         
         NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
         [body setStringValue:body_str];
         NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
         [message addAttributeWithName:@"type" stringValue:@"chat"];
         [message addAttributeWithName:@"to" stringValue:toStr];
         [message addChild:body];

        
         
         NSLog(@"发送消息给XMPP:%@",message);
         
         [_xmppStream sendElement:message];
    }

        
}
#pragma mark XMPPStream Delegate

//socket连接建立成功
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(RCDAsyncSocket *)socket
{
    NSLog(@"socket连接建立成功");
}

//连接成功到服务器
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    NSError *authError = nil;
    if (![_xmppStream authenticateWithPassword:thePasswrod error:&authError]) {
        if (authError) {
            NSLog(@" -- 服务器密码难证错误：%@",authError);
        }
    }
}

//登录验证成功
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    //上线--更改状态

    [self goOnLine];
    
}

//验证登录失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@" -- 验证登录错误：%@",error);
}

//收到信息
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    
    /*
    if ([message isChatMessageWithBody])
    {
        
        NSString *body = [[message elementForName:@"body"] stringValue];
        NSString *displayName = [[message from] user];
        
        if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
                                                                message:body
                                                               delegate:nil
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
        else
        {
            // We are not active, so use a local notification instead
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            localNotification.alertAction = @"Ok";
            localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,body];
            
            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
        }
    }
     
     */
    
    if ([self.delegate respondsToSelector:@selector(didReceiveMessage:)]) {
        [self.delegate didReceiveMessage:message];
    }
    
    

}

//好友在线状态
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    //取得好友状态
    NSString *presenceType = [presence type]; //online/offline
    NSString *userId = [[sender myJID] user];
    NSString *presenceFromUser = [[presence from] user];
    //NSLog(@" -- 用户状态：%@ %@",presenceFromUser,presenceType);
    
    if (![presenceFromUser isEqualToString:userId]) {
        
        //在线状态
        if ([presenceType isEqualToString:@"available"]) {
            
            if ([self.delegate respondsToSelector:@selector(newUserOnline:)]) {
                [self.delegate newUserOnline:presence];
            }
        }
        else if ([presenceType isEqualToString:@"unavailable"]) {
            
            if ([self.delegate respondsToSelector:@selector(hasUserOffline:)]) {
                [self.delegate hasUserOffline:presence];
            }
            
        }
        
        
    }
}

//收到连接错误
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
    NSLog(@" ** 收到 Stream 错误 %@",error);
}

//断开连接发生错误
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    NSLog(@" ** 断开服务器连接 错误 %@",error.localizedDescription);

}


@end
